package com.youwu.weather.service.impl;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.youwu.weather.service.CityDataService;
import com.youwu.weather.service.WeatherDataService;
import com.youwu.weather.vo.City;
import com.youwu.weather.vo.WeatherResponse;
import com.youwu.weather.vo.WeatherType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * WeatherDataService 实现.
 */
@Service
public class WeatherDataServiceImpl implements WeatherDataService {

    private static Logger logger = LoggerFactory.getLogger(WeatherDataServiceImpl.class);
    private static final String WEATHER_URI = "https://free-api.heweather.net/s6/weather/";
    private static final String KEY = "1fba98d5c3954585a4571eb4d1c179ae";
    private static final long TIME_OUT = 1800L;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CityDataService cityDataService;

    @Override
    public WeatherResponse getDataByCityName(WeatherType weatherType, String cityName) {
        String uri = WEATHER_URI + weatherType.type + "?location=" + cityName + "&key=" + KEY;
        return this.doGetWeahter(uri);
    }

    private WeatherResponse doGetWeahter(String uri) {
        String key = uri;
        String strBody = null;
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        // 先查缓存，缓存有取缓存数据
        if (stringRedisTemplate.hasKey(key)) {
            logger.info("have data");
            strBody = ops.get(key);
        } else {
            logger.info("don't have data");
            // 缓存没有，再调用服务接口获取数据，并将数据加入到缓存中
            ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);

            if (respString.getStatusCodeValue() == 200) {
                strBody = respString.getBody();
            }

            // 数据写入缓存中
            ops.set(key, strBody, TIME_OUT, TimeUnit.SECONDS);
        }

        ObjectMapper mapper = new ObjectMapper();
        WeatherResponse resp = null;

        try {
            resp = mapper.readValue(strBody, WeatherResponse.class);
        } catch (IOException e) {
            logger.info("Exception");
        }
        return resp;
    }

    @Override
    public void syncDataByCity(WeatherType weatherType, String city) {
        String uri = WEATHER_URI + weatherType.type + "?location=" + city + "&key=" + KEY;
        this.saveWeatherData(uri);
    }

    private void saveWeatherData(String uri) {
        String key = uri;
        String strBody = null;
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);

        if (respString.getStatusCodeValue() == 200) {
            strBody = respString.getBody();
        }

        // 数据写入缓存中
        ops.set(key, strBody, TIME_OUT, TimeUnit.SECONDS);
    }

}
